<template>
  <div id="app">
    <nav class="top-navbar" :class="{ fixed: isSticky }">
      <div class="back">&lt;</div>
      <div class="nav-right">
        <a href="/main/home" class="nav-link">首页</a>
        <a href="/main/profile" class="nav-link">个人中心</a>
        <a href="#" class="nav-link">购物车</a>
        <a href="#" class="nav-link">收藏夹</a>
        <a href="#" class="nav-link">帮助中心</a>
        <button class="sign-in-button" @click="showLoginDialog = true">
          Sign in
        </button>
        <button class="register-button" @click="showRegisterDialog = true">
          Register
        </button>
        <button v-if="isLoggedIn" class="sign-out-button" @click="logout">
          Sign out
        </button>
      </div>
    </nav>
    <div class="shopping-cart">
      <div class="left-panel">
        <h2>总计</h2>
        <ul class="left-list">
          <li v-for="(item, index) in selectedProducts" :key="index">
            {{ item.count > 1? `${item.name} x${item.count}` : item.name }}
          </li>
        </ul>
        <button class="total-button" @click="checkout">结算</button>
        <span class="total-price">¥{{ totalPrice }}</span>
        <button
          class="delete-selected-button"
          @click="deleteSelectedProducts"
          :disabled="!hasSelectedProducts"
        >
          删除选中商品
        </button>
      </div>
      <div class="right-panel">
        <div class="filter-search">
          <button class="all-button" @click="selectAllProducts">all</button>
          <input
            type="text"
            placeholder="search"
            class="search-input"
            v-model="searchKeyword"
          />
          <button class="search-icon">
            <i class="fas fa-search">🔍</i>
          </button>
        </div>
        <div class="product-list">
          <div
            class="product-item"
            v-for="(product, index) in filteredProducts"
            :key="index"
          >
            <input type="checkbox" v-model="product.isChecked" @change="calculateTotal" />
            <img :src="product.image_url" alt="product" class="product-image" />
            <div class="product-info">
              <span class="product-name">{{ product.name }}</span>
              <span class="product-price">¥{{ product.price * product.quantity }}</span>
              <input
                type="number"
                v-model.number="product.quantity"
                @input="calculateTotal"
                min="1"
                class="quantity-input"
              />
              <button class="delete-button" @click="deleteSingleProduct(index)">
                delete
              </button>
            </div>
          </div>
        </div>
      </div>
    </div>
    <LoginDialog v-if="showLoginDialog" @close="showLoginDialog = false" />
    <RegisterDialog
      v-if="showRegisterDialog"
      @close="showRegisterDialog = false"
    />
  </div>
</template>

<script setup>
import { ref, onMounted, onBeforeUnmount, computed } from "vue";
import LoginDialog from "../../components/LoginDialog.vue";
import RegisterDialog from "../../components/RegisterDialog.vue";

// 定义响应式数据
const showLoginDialog = ref(false);
const showRegisterDialog = ref(false);
const isLoggedIn = ref(localStorage.getItem("isLoggedIn") === "true");

// 退出登录
const logout = () => {
  localStorage.removeItem("isLoggedIn");
  localStorage.removeItem("currentUser");
  isLoggedIn.value = false;
  // 若未引入 ElMessage 会报错，可根据实际情况替换
  // ElMessage.success("退出成功");
};

const products = ref([]);
const totalPrice = ref(0);
const isSticky = ref(false);
const searchKeyword = ref("");

// 计算属性：过滤商品
const filteredProducts = computed(() => {
  if (!searchKeyword.value) {
    return products.value;
  }
  return products.value.filter((product) =>
    product.name.toLowerCase().includes(searchKeyword.value.toLowerCase())
  );
});

// 计算属性：获取选中的商品并合并相同商品
const selectedProducts = computed(() => {
  const selected = products.value.filter((product) => product.isChecked);
  const merged = [];
  selected.forEach((product) => {
    const existingProduct = merged.find((p) => p.product_id === product.product_id);
    if (existingProduct) {
      existingProduct.count++;
    } else {
      merged.push({ ...product, count: 1 });
    }
  });
  return merged;
});

// 计算属性：判断是否有选中的商品
const hasSelectedProducts = computed(() => {
  return selectedProducts.value.length > 0;
});

// 滚动事件处理函数
const handleScroll = () => {
  if (window.pageYOffset > 0) {
    isSticky.value = true;
  } else {
    isSticky.value = false;
  }
};

// 计算总价函数
const calculateTotal = () => {
  totalPrice.value = selectedProducts.value.reduce(
    (sum, product) => sum + product.price * product.quantity,
    0
  );
};

// 删除单个商品函数
const deleteSingleProduct = (index) => {
  filteredProducts.value.splice(index, 1);
  calculateTotal();
};

// 删除选中商品函数
const deleteSelectedProducts = () => {
  products.value = products.value.filter((product) => !product.isChecked);
  calculateTotal();
};

// 全选商品函数
const selectAllProducts = () => {
  const allChecked = filteredProducts.value.every(
    (product) => product.isChecked
  );
  filteredProducts.value.forEach((product) => {
    product.isChecked = !allChecked;
  });
  calculateTotal();
};

// 结算函数，这里可以添加实际的结算逻辑
const checkout = () => {
  console.log('进行结算操作，总价：', totalPrice.value);
  // 可以在这里添加更多结算逻辑，如调用后端接口等
};

// 挂载时绑定滚动事件并加载数据
onMounted(async () => {
  window.addEventListener("scroll", handleScroll);
  try {
    const response = await fetch("/Carts.json");
    console.log('Response status:', response.status);  // 打印状态码
    console.log('Response headers:', response.headers);  // 打印响应头

    if (!response.ok) {
      throw new Error(`HTTP error! status: ${response.status}`);
    }
    const contentType = response.headers.get('content-type');
    if (!contentType || !contentType.includes('application/json')) {
      throw new Error('Response is not in JSON format');
    }
    const data = await response.json();
    console.log('Response data:', data);  // 打印解析后的 JSON 数据
    products.value = data.cart.items.map((product) => ({ ...product, isChecked: false }));
    calculateTotal(); // 初始化时计算总价
  } catch (error) {
    console.error("Error fetching data:", error);
  }
});

// 卸载前移除滚动事件
onBeforeUnmount(() => {
  window.removeEventListener("scroll", handleScroll);
});
</script>

<style scoped>
/* * {
  margin: 0 auto;
  padding: 0;
} */
#app {
  width: 100vw;
  height: auto;
  margin: 0;
  font-family: Avenir, Helvetica, Arial, sans-serif;
  padding: 0rem;
  text-align: center;
  color: #2c3e50;
}
.top-navbar {
  display: flex;
    justify-content: space-between;
    align-items: center;
    background-color: #f4f4f4;
    padding: 10px 20px;
    position: fixed;
    top: 0;
    left: 0;
    right: 0;
    z-index: 1000;
    box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
}
.nav-link:hover {
  color: white;
  background-color: #333;
  border-radius: 20%;
}
/* .fixed {
  position: sticky;
  top: 0;
  width: 100%;
  background-color: #f4f4f4;
  box-shadow: 0 2px 4px rgba(0, 0, 0, 0.1);
} */
.nav-link {
  margin-right: 20px;
  text-decoration: none;
  color: #333;
}
.sign-in-button,
.register-button,
.sign-out-button {
  background-color: #333;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}
.shopping-cart {
  margin-top: 50px;
  display: flex;
  width: 100%;
  height: 100vh;
}
.left-panel {
  width: 240px;
    padding: 20px 0;
    border-right: 1px solid #eee;
    background-color: #f9f9f9;
    position: fixed;
    top: 60px;
    bottom: 0;
    left: 20px;
    overflow-y: auto;
    box-shadow: 2px 0 4px rgba(0, 0, 0, 0.1);
}
.right-panel {
  flex: 1;
    padding: 20px;
    margin-left: 350px;
    max-width: 1200px;
    margin-right: auto;
    margin-top: -20px;
    display: flex;
    flex-direction: column;
}
.filter-search {
  display: flex;
    align-self: center;
    margin-bottom: 20px;
    margin-top: 20px;
    width: 30rem;
}
.all-button {
  margin-right: 10px;
  padding: 5px 10px;
  background-color: #333;
  color: white;
  border: none;
  cursor: pointer;
}
.search-input {
  flex: 1;
  padding: 5px;
  border-radius: 5px;
}
.search-icon {
  padding: 5px 10px;
  background-color: #fff;
  border: 1px solid #ccc;
  cursor: pointer;
}
.product-list {
  display: flex;
  flex-direction: column;
}
.product-item {
  width: calc(90% - 20px);
    margin-bottom: 20px;
    border: 1px solid #ccc;
    padding: 10px;
    box-sizing: border-box;
    display: flex;
    border-radius: 10px;
    align-items: center;
    background-color: #f5fbff;
}
.product-image {
  width: 100px;
  height: 100px;
  border-radius: 10px;
}
.product-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
  margin-left: 10px;
}
.delete-button {
  background-color: #333;
  color: white;
  border: none;
  padding: 5px 10px;
  cursor: pointer;
}
.total-button {
  width: 100%;
  padding: 10px;
  background-color: #333;
  color: white;
  border: none;
  cursor: pointer;
  margin-top: 20px;
}
.delete-selected-button {
  width: 100%;
  padding: 10px;
  background-color: #333;
  color: white;
  border: none;
  cursor: pointer;
  margin-top: 20px;
  opacity: 0.5;
  pointer-events: none;
}
.delete-selected-button:enabled {
  opacity: 1;
  pointer-events: auto;
}
.left-list {
  list-style: none;
    margin-right: 40px;
}
.quantity-input {
  width: 50px;
  padding: 5px;
  margin-left: 10px;
}
</style>  